'use strict'
let router = require('koa-router')();
let fs = require('fs');
let path = require('path');

function f1(params) {
    let Fpath = params || __dirname;

    let Farr = fs.readdirSync(Fpath);

    let result = Farr.filter(i => {
        return i.endsWith('.js') && i !== 'index.js'
    });

    return result;
}

function f2(router, result) {
    result.forEach(i => {
        let Fpath = require(path.join(__dirname, i));

        for (const key in Fpath) {
            let Skey = key.split(' ');

            let rou_method = Skey[0];
            let rou_url = Skey[1];
            let rou_fun = Fpath[key];

            // console.log(rou_method);
            // console.log(rou_url);
            // console.log(rou_fun);

            if (rou_method === 'get') {
                router.get(rou_url, rou_fun)
            } else if (rou_method === 'post') {
                router.post(rou_url, rou_fun)
            } else if (rou_method === 'put') {
                router.put(rou_url, rou_fun)
            } else if (rou_method === 'delete') {
                router.delete(rou_url, rou_fun)
            }
        }
    });
    return router.routes();
}

module.exports = () => {
    let fn1 = f1();
    let fn2 = f2(router, fn1);

    return fn2;
}
